package com.lwc.vhr.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Component
@Slf4j
public class CustomUrlDecisiionManager implements AccessDecisionManager {
    /**
     * 决定是否放行
     * @param authentication 当前登录用户的信息
     * @param object
     * @param configAttributes Filter过滤后返回的角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //遍历过滤后的角色是否在authentication中
        for (ConfigAttribute configAttribute : configAttributes){
            //所需要的角色
            String needRole = configAttribute.getAttribute();
//            log.info("当前所需的角色为：{}",needRole);
            //如果是登陆即可访问的路径则查看是否登陆即可
            if ("ROLE_LOGIN".equals(needRole)){
                if (authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录！");
                }else {
                    return;
                }
            }
            //获取当前登录用户的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //判断当前登陆用户是否包含所要求的角色中的任意一项
            for (GrantedAuthority authority : authorities) {
//                log.info("当前角色为：{}，所需的角色:{}",authority.getAuthority(),needRole);
                //如果当前登陆用户的角色中有所需的角色
                if (authority.getAuthority().equals(needRole)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aclass) {
        return true;
    }
}
